package com.ecarx.camera.ui.main.adapter;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.ecarx.camera.ui.camera.CameraFragment;
import com.ecarx.camera.ui.settings.SettingsFragment;

public class MainFragmentStateAdapter extends FragmentStateAdapter {

    private static final int ITEM_COUNT = 2;
    public static final int POS_CAMERA = 0;
    public static final int POS_SETTINGS = 1;

    private final Bundle arguments;

    private CameraFragment mCameraFragment;
    private SettingsFragment mSettingsFragment;
    private Fragment defaultFragment;

    public CameraFragment getCameraFragment() {
        return mCameraFragment;
    }

    public SettingsFragment getSettingsFragment() {
        return mSettingsFragment;
    }

    public MainFragmentStateAdapter(@NonNull Fragment fragment) {
        super(fragment);
        arguments = fragment.getArguments();
        initFragment();
    }

    private void initFragment(){
        if(mCameraFragment == null){
            mCameraFragment = new CameraFragment();
            mCameraFragment.setArguments(arguments);
        }
        if(mSettingsFragment == null){
            mSettingsFragment = new SettingsFragment();
            mSettingsFragment.setArguments(arguments);
        }
        if(defaultFragment == null){
            defaultFragment = new Fragment();
            defaultFragment.setArguments(arguments);
        }
    }

    private Fragment getFragmentByPosition(int position){
        switch (position) {
            case POS_CAMERA:
                if(mCameraFragment == null){
                    mCameraFragment = new CameraFragment();
                    mCameraFragment.setArguments(arguments);
                }
                return mCameraFragment;
            case POS_SETTINGS:
                if(mSettingsFragment == null){
                    mSettingsFragment = new SettingsFragment();
                    mSettingsFragment.setArguments(arguments);
                }
                return mSettingsFragment;
            default:
                if(defaultFragment == null){
                    defaultFragment = new Fragment();
                    defaultFragment.setArguments(arguments);
                }
                return defaultFragment;
        }
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return getFragmentByPosition(position);
    }

    @Override
    public int getItemCount() {
        return ITEM_COUNT;
    }
}
